package com.alibaba.dongbao.controller.ums;

import com.alibaba.dongbao.base.Code.CodeMsg;
import com.alibaba.dongbao.base.result.Result;
import com.baomidou.kaptcha.Kaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

/**
 * @Author: Mr.ZJW
 * @Date: 2022-04-23 11:30
 * @Description: Kaptcha生成验证码接口
 */
@RestController
@RequestMapping("/kaptcha")
public class KaptchaController {

    @Autowired
    private Kaptcha kaptcha;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * @Author: Mr.ZJW
     * @Description: 生成验证码
     * @Date: 2022/4/25 10:49
     **/
    @GetMapping("/render")
    public void render() {
        //生成
        String render = kaptcha.render();
        //存放到Redis
        redisTemplate.opsForValue().set("code", render);
    }

    /**
     * @Author: Mr.ZJW
     * @Description: 解析验证码
     * @Date: 2022/4/25 10:49
     **/
    @PostMapping("/valid")
    public Result validDefaultTime(@RequestParam String code) {
        //验证码设置60秒过期
        boolean validate = kaptcha.validate(code, 60);
        if (validate) {
            redisTemplate.delete("code");
            return Result.success(CodeMsg.LOGIN_SUCCESS_CODE);
        }
        return Result.error(CodeMsg.LOGIN_ERROR_CODE);
    }

}
